<template>
  <view class="device-connect-page">
    <nav-bar title="设备连接" color="white" show-back bg-color="black"></nav-bar>
    <view class="flex-auto">
      <u-row gutter="0" custom-style="height: 90vh">
        <u-col span="2" custom-style="border-right: 1px solid #ccc;height: 100%;">
          <view
            v-for="item in deviceType"
            :key="item.id"
            :class="{ 'device-type': true, active: currentDeviceType === item.id }"
            @click="changheTab(item)"
          >
            <u-icon
              :custom-prefix="item.iconprefix || 'uicon'"
              :name="item.icon || ''"
              size="12rpx"
              color="inherit"
              bold
            ></u-icon>
            <view class="px-5rpx">
              <u-text :text="item.name" size="10rpx" color="inherit" bold></u-text>
            </view>
          </view>
        </u-col>
        <u-col span="10">
          <!-- 打印机管理 -->
          <view class="printer-manage" v-if="currentDeviceType === 'DYJ001'">
            <view class="w-full">
              <view class="flex justify-between">
                <view class="flex">
                  <u-text text="打印机" bold size="11rpx"></u-text>
                  <text @click="refreshPrinter" class="text-blue-500 font-bold ml-10rpx">刷新</text>
                </view>
                <view @click="toPrinterSettingPage"><text class="text-blue-500 font-bold">打印设置</text></view>
              </view>
              <view class="py-10rpx">
                <u-text text="我的打印机（当前只显示usb连接的打印机）" type="info"></u-text>
              </view>
              <u-line margin="0.5em 0" />

              <view class="device-list">
                <view v-for="item in deviceList" :key="item.id" class="device-item">
                  <view class="flex justify-between mb-5rpx" @click="printTest(item)">
                    <u-text :text="item.name" bold size="11rpx"></u-text>
                  </view>
                  <view class="flex justify-between">
                    <u-text :text="item.printSize || '-'" type="info" align="center"></u-text>
                    <text class="text-gray-300">|</text>
                    <u-text :text="item.details?.ProductName" type="info" align="center" lines="1"></u-text>
                    <text class="text-gray-300">|</text>
                    <u-text :text="item.details?.Version" type="info" align="center"></u-text>
                  </view>
                  <!-- 用途 -->
                  <view class="py-10rpx">
                    <view v-for="t in printServiceAreaType" :key="t.name" class="mr-5rpx inline-block">
                      <u-tag
                        :text="t.name"
                        :type="areaTypeStaus(item, t.name) ? 'success' : 'info'"
                        size="mini"
                        @click="setAreaTypeStatus(t, item)"
                      ></u-tag>
                    </view>
                  </view>
                  <!-- <u-text :text="item.statusText" :type="item.status || 'info'"></u-text> -->
                </view>
                <u-empty
                  v-if="deviceList.length === 0"
                  mode="data"
                  width="200rpx"
                  height="200rpx"
                  text=" "
                  :icon="'/static/images/state/state_no_search.png'"
                ></u-empty>
              </view>
            </view>
          </view>
          <!-- 未知设备管理 -->
          <view class="printer-manage" v-else-if="currentDeviceType === 'NULL-DEV'">
            <view class="w-full">
              <!-- <view class="flex justify-between">
                <u-text text="打印机" bold size="11rpx"></u-text>
                <view @click="toPrinterSettingPage"><text class="text-blue-500 font-bold">打印设置</text></view>
              </view>
              <view class="py-10rpx">
                <u-text text="我的打印机（当前只显示usb连接的打印机）" type="info"></u-text>
              </view>
              <u-line margin="0.5em 0" /> -->

              <view class="device-list">
                <view v-for="item in deviceList" :key="item.id" class="device-item">
                  <view class="flex justify-between mb-5rpx">
                    <u-text :text="item.name" bold size="11rpx"></u-text>
                  </view>
                  <view class="flex justify-between">
                    <u-text :text="item.details?.ProductName" type="info" align="center" lines="1"></u-text>
                    <text class="text-gray-300">|</text>
                    <u-text :text="item.details?.Version" type="info" align="center"></u-text>
                  </view>
                </view>
                <u-empty
                  v-if="deviceList.length === 0"
                  mode="data"
                  width="200rpx"
                  height="200rpx"
                  text=" "
                  :icon="'/static/images/state/state_no_search.png'"
                ></u-empty>
              </view>
            </view>
          </view>
          <view v-else>
            <u-empty
              mode="data"
              width="200rpx"
              height="200rpx"
              text=" "
              :icon="'/static/images/state/state_no_search.png'"
            ></u-empty>
          </view>
        </u-col>
      </u-row>
    </view>
  </view>
</template>
<script setup>
import { asyncExecFunction } from "@/king-components/js/KingonPlus";
import { computed, onMounted, reactive, ref } from "vue";
import POSConnect from "@/pages/subReportForm/print-config/POSConnect";

import { useStore } from "vuex";

const store = useStore();

// 设备分类
const deviceType = ref([
  {
    name: "打印机",
    id: "DYJ001",
    icon: "printer",
    iconprefix: "iconzhucan",
  },
  {
    name: "未知设备",
    id: "NULL-DEV",
    icon: "question-circle",
  },
  // {
  //   name: "扫描枪",
  //   id: "SMG0001",
  // },
  // {
  //   name: "读卡器",
  //   id: "DKQ0001",
  // },
]);
// 当前选中设备分类
const currentDeviceType = ref("DYJ001");
// 设备分类变更
const changheTab = async (item) => {
  currentDeviceType.value = item.id;
  switch (item.id) {
    case "DYJ001":
      deviceList.value = store.getters.usbPrinterList;
      break;
    case "NULL-DEV":
      try {
        // 获取usb设备列表
        const res = await asyncExecFunction("HnXfjGetUsbPrinterList", {
          isFilter: false,
        });

        // 将设备信息转换为设备列表 deviceList
        const devices = JSON.parse(res);
        deviceList.value = Object.keys(devices).map((key) => {
          const device = devices[key];
          return {
            id: device.DeviceId,
            path: device.DeviceName,
            name: device.DeviceName,
            serialNumber: device.SerialNumber,
            printSize: "",
            printerType: "usb",
            status: "null",
            statusText: "-",
            details: device,
          };
        });
      } catch (error) {
        console.error(error);
        uni.showToast({
          title: "获取设备失败",
          icon: "error",
        });
      }
      break;
    default:
      break;
  }
};

// 对应设备分类的设备列表

// 打印机甚至可以分为  usb打印机，蓝牙/wifi打印机, 云端打印机， 管理方式（查询/连接/打印）完全不同
const deviceList = ref([
  // {
  //   id: "aacc",
  //   name: "未知型号",
  //   printSize: "48mm",
  //   purpose: ["前台", "后厨"],
  //   printerType: "usb",
  //   status: "success",
  //   statusText: "已连接",
  // },
  // {
  //   id: "aacc",
  //   name: "未知型号",
  //   printSize: "50mm",
  //   purpose: [],
  //   printerType: "usb",
  // },
  // {
  //   id: "aacc",
  //   name: "未知型号",
  //   printSize: "55mm",
  //   purpose: [],
  //   printerType: "usb",
  // },
]);

// 打印服务区域类型
const printServiceAreaType = reactive([
  { name: "前台", id: "QD" },
  { name: "后厨", id: "HC" },
]);

// 获取打印服务状态
const areaTypeStaus = computed(() => {
  return (item, name) => {
    return item?.purpose.includes(name);
  };
});

// 设置状态
const setAreaTypeStatus = (t, item) => {
  try {
    // 如果有则去除,没有则新增
    if (item.purpose.includes(t.name)) {
      item.purpose = item.purpose.filter((i) => i !== t.name);
    } else {
      item.purpose.push(t.name);
    }

    // 按理说还要更新一下 本地数据中 的 打印区域存在的打印机列表,
    // 然后打印时根据 打印区域的设置查找打印区域的设备列表,根据设备类型触发相应打印操作
    store.commit("print/updatePrintArea", item);
  } catch (error) {
    console.error(error);
  }
};

onMounted(async () => {
  changheTab(deviceType.value[0]);
});

// 重新初始化打印机
async function refreshPrinter() {
  console.debug("refreshPrinter");
  deviceList.value = [];
  await store.dispatch("print/usbPrinterInit");
  deviceList.value = store.getters.usbPrinterList;
}

function toPrinterSettingPage() {
  uni.navigateTo({
    url: "/pages/subReportForm/print",
  });
}

// 打印测试
async function printTest(item) {
  try {
    const arr = [];
    arr.push({
      ActionType: "PrintText",
      Parameter: "打印测试....",
    });
    const PrintData = {
      PrintData: arr,
      DevicePath: item.path,
    };
    const Arg = JSON.stringify(PrintData);
    // 创建连接
    const createResult = await asyncExecFunction("KoCreatePrinter", {
      DeviceType: POSConnect.DEVICE_TYPE_USB,
      DevicePath: item.path,
    });
    console.log("createResult>", createResult);
    // 打印票据
    const printResult = await asyncExecFunction("koPrintReceipt", Arg);
    console.log("printResult>", printResult);
    uni.showToast({
      title: "打印完成",
      icon: "success",
    });
  } catch (error) {
    console.error(error);
    uni.showToast({
      title: "打印失败",
      icon: "error",
    });
  }
}
</script>
<style lang="scss" scoped>
.device-connect-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  .device-type {
    width: 100%;
    height: 40rpx;
    display: flex;
    justify-content: center;
    align-items: center;

    &.active {
      background-color: var(--kui-color-theme);
      color: white;
    }
  }
}

/** 打印机管理 */
.printer-manage {
  display: flex;
  height: 90vh;
  // background-color: red;
  padding: 20rpx;
  box-sizing: border-box;

  .device-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    .device-item {
      padding: 10rpx;
      border-radius: 8rpx;
      background-color: var(--kui-color-bg);
      border: 1px solid rgb(187, 187, 187);
      display: flex;
      flex-direction: column;
      width: 130rpx;
      min-width: 130rpx;
      margin-right: 10rpx;
      margin-bottom: 10rpx;
    }
  }
}
</style>
